<?php

namespace app\admin\model;

use app\common\model\level\UserLevel;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\UserCensusCount;
use think\Model;

class User extends Model
{

    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'prevtime_text',
        'logintime_text',
        'jointime_text',
        'count',

        'is_comment_txt',
        'is_give_txt',
        'is_collect_txt',

        'is_speak_me_txt',
        'is_comment_me_txt',
        'is_private_txt',
        'is_mail_txt',

    ];


    public function getIsCommentTxtAttr($value, $data)
    {
        $list = ['0' => '默认设置（所有人都可评论）', '1' => '所有人可评论（不包括黑名单会员）', '2' => '我关注的人可评论'];
        return isset($list[$data['is_comment']]) ? $list[$data['is_comment']] : '';
    }

    public function getIsGiveTxtAttr($value, $data)
    {
        $list = ['0' => '默认设置（所有人都可点赞）', '1' => '所有人可点赞（不包括黑名单会员）', '2' => '我关注的人可点赞'];
        return isset($list[$data['is_give']]) ? $list[$data['is_give']] : '';
    }

    public function getIsCollectTxtAttr($value, $data)
    {
        $list = ['0' => '默认设置（所有人都可收藏）', '1' => '所有人可收藏（不包括黑名单会员）', '2' => '我关注的人可收藏'];
        return isset($list[$data['is_give']]) ? $list[$data['is_give']] : '';
    }

    /** 通知设置开始 */
    public function getIsSpeakMeTxtAttr($value, $data)
    {
        $list = ['0' => '默认设置（接收系统邮件）', '1' => '接收系统邮件', '2' => '不接收系统邮件'];
        return isset($list[$data['is_speak_me']]) ? $list[$data['is_speak_me']] : '';
    }

    public function getIsCommentMeTxtAttr($value, $data)
    {
        $list = ['0' => '默认设置（接收系统邮件）', '1' => '接收系统邮件', '2' => '不接收系统邮件'];
        return isset($list[$data['is_comment_me']]) ? $list[$data['is_comment_me']] : '';
    }

    public function getIsPrivateTxtAttr($value, $data)
    {
        $list = ['0' => '默认设置（接收系统邮件）', '1' => '接收系统邮件', '2' => '不接收系统邮件'];
        return isset($list[$data['is_private']]) ? $list[$data['is_private']] : '';
    }

    public function getIsMailTxtAttr($value, $data)
    {
        $list = ['0' => '默认设置（从不接收）', '1' => '从不接收', '2' => '每天接收', '3' => '每周接收', '4' => '每月接收'];
        return isset($list[$data['is_mail']]) ? $list[$data['is_mail']] : '';
    }

    /** 通知设置结束 */
    public function getCountAttr($value, $data)
    {
        return UserCensusCount::where('user_id', $data['id'])->field(['user_id', 'user_fans_count', 'user_follow_count', 'user_trends_count', 'user_collect_count'])->find();
    }


    public function getOriginData()
    {
        return $this->origin;
    }

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }
        });


        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            $origin = $row->getOriginData();
            if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (double)$changedata['money'] !== (double)$origin['money'])) {
                MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
            }
            if (isset($changedata['score']) && (int)$changedata['score'] !== (int)$origin['score']) {
                ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
            }
        });

    }

    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['prevtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['logintime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['jointime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setBirthdayAttr($value)
    {
        return $value ? $value : null;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function merchant()
    {
        return $this->belongsTo('Admin', 'merchant_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function lvl()
    {
        return $this->belongsTo(UserLevel::class, 'level', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 分类
     * @param $value
     * @param $data
     * @return string
     * @author yuncran@126.com
     */
    public function getTypeList()
    {
        return UserLevel::field('id,title')->select();
    }

}
